//
//  MessageAlertViewController.m
//  EducationAdminClient
//
//  Created by KWSD_F on 16/4/18.
//  Copyright © 2016年 周佳兴. All rights reserved.
//

#import "MessageAlertViewController.h"
#import "MessageModel.h"
#import "MessageTableViewCell.h"
#import "DetailViewController.h"
#import "MJRefresh.h"
@interface MessageAlertViewController ()<secondViewDelegate>
{
    NSInteger _limit;
    NSInteger _leftStart;
    NSInteger _rightStart;
    NSInteger _start;
    BOOL _ifNeedRefresh;//是否需要刷新左侧列表
    BOOL _isFirstSelectRightBtn;
    BOOL _isRefresh;
    BOOL _editStage;//编辑状态为YES，非编辑状态为NO
    BOOL _isMore;//下拉加载状态
    //    NSIndexPath *_indexPath;
}
@end
//[self.myTableView setEditing:YES animated:YES];


@implementation MessageAlertViewController


//-(void)viewWillAppear:(BOOL)animated{
//    if (_indexPath) {
//        [self.tbView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:_indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
//    }
//
//}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (self.openSwitch == 1) {
        NSLog(@"正在已读列表");
    }else{
        //        _isRefresh = YES;
        //        [self dataRequest];
    }
    
}
-(void)showName:(NSString *)nameString andFlag:(BOOL)isNeedRefresh{
    NSLog(@"%@",nameString);
    if ([nameString isEqualToString:@"read"]) {
        NSLog(@"不需要刷新");
    }else if([nameString isEqualToString:@"other"]){
        NSLog(@"需要刷新");
        if (isNeedRefresh == YES) {
            if (_openSwitch == 0) {
                [_leftArr removeAllObjects];
                _isFirstSelectRightBtn = YES;
                [self dataRequest];
            }else{
                [_rightArr removeAllObjects];
                _ifNeedRefresh = YES;//当前所在列表是已读列表，点击未读列表时需要刷新，所以要改变刷新判定值
                [self dataRequest];
                
            }
            //            [self dataRequest];
        }else{
            NSLog(@"什么鬼👻");
        }
        
    }else{
        NSLog(@"什么鬼");
    }
}
- (NSMutableArray *)pickDeleteIndexArr{
    if (!_pickDeleteIndexArr) {
        _pickDeleteIndexArr = [[NSMutableArray alloc] init];
    }
    return _pickDeleteIndexArr;
}

- (UIView *)bgLineView{
    if (!_bgLineView) {
        _bgLineView = [[UIView alloc] init];
        _bgLineView.backgroundColor = [UIColor colorWithHex:0xe6e6e6];
        
        [self.view addSubview:_bgLineView];
        [_bgLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.top.equalTo(self.rightBtn.mas_bottom);
            make.height.equalTo(@(3));
            make.right.equalTo(self.view.mas_right);
        }];
        
        
    }
    return _bgLineView;
}

- (UIView *)selectbgView{
    if (!_selectbgView) {
        _selectbgView = [[UIView alloc] init];
        _selectbgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_selectbgView];
        [_selectbgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom);
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.height.equalTo(@(40));
        }];
    }
    
    return _selectbgView;
}

- (UIView *)lineView{
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        [self.bgLineView addSubview:_lineView];
        [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.bgLineView.mas_top);
            make.height.equalTo(self.bgLineView.mas_height);
            make.centerX.equalTo(self.leftBtn.mas_centerX);
            make.width.equalTo(@(70));
        }];
        
    }
    return _lineView;
}

- (UIButton *)leftBtn{
    if (!_leftBtn) {
        _leftBtn = [[UIButton alloc] init];
        [self.view addSubview:_leftBtn];
        [_leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top);
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_centerX);
            make.height.equalTo(@(40));
        }];
        [_leftBtn setTitleColor:[UIColor colorWithHex:0x5da6ff] forState:UIControlStateNormal];
        [_leftBtn setTitle:@"未读" forState:UIControlStateNormal];
        _leftBtn.titleLabel.font = [UIFont systemFontOfSize:32/2];
        
    }
    
    return _leftBtn;
}

- (UIButton *)rightBtn{
    if (!_rightBtn) {
        _rightBtn = [[UIButton alloc] init];
        
        
        [self.view addSubview:_rightBtn];
        
        
        [_rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top);
            make.left.equalTo(self.view.mas_centerX);
            make.right.equalTo(self.view.mas_right);
            make.width.equalTo(_leftBtn.mas_width);
            make.height.equalTo(@(40));
        }];
        [_rightBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
        [_rightBtn setTitle:@"已读" forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:32/2];
    }
    return _rightBtn;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _isRefresh = NO;//是否是刷新
    _limit = 20;//设置一次请求的消息数量
    _leftStart = 0;//设置左侧未读消息第一次请求的消息开始位置
    _rightStart = 0;//设置右侧已读消息第一次请求的消息开始位置
    _start = 0;//设置第一次请求默认从零开始
    _openSwitch = 0;//设置第一次是未读列表
    _ifNeedRefresh = NO;//设置默认左侧不需要刷新
    _leftArr = [[NSMutableArray alloc]init];
    _rightArr = [[NSMutableArray alloc]init];
    _isFirstSelectRightBtn = YES;//第一次点击右侧的btn
    _editStage = NO;//编辑模式
    [self setTitleLabelText:@"消息通知"];
    
    
    
    [self createLeftNavBar];
    self.view.backgroundColor =  [UIColor colorWithHex:0xf4f4f4];
    
    
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 35, 37/2);
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightBtn setTitle:@"删除" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    _sourceArr = [[NSMutableArray alloc]init];
    //*** createUI
    [self createUI];
    
    //*** dataRequest
    [self dataRequest];
    
    
}


#pragma mark - 数据请求
-(void)dataRequest{
    if(self.requeatResultLabel)[self.requeatResultLabel removeFromSuperview];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    if(_openSwitch == 0)
    {
        [param setObject:[NSString stringWithFormat:@"%zd",_leftStart] forKey:@"start"];
    }else{
        [param setObject:[NSString stringWithFormat:@"%zd",_rightStart] forKey:@"start"];
    }
    [param setObject:[NSString stringWithFormat:@"%zd",_limit] forKey:@"limit"];
    
    [param setObject: getSessionId() forKey:@"sessionId"];
    
    //    _start = _start + _limit;
    NSLog(@"%@",param);
    NSString *requestStr = [NSString stringWithFormat:@"%@%@", getBase(), MESSAGE];
    [NetRequest requestUrl:requestStr andParamas:param andReturnBlock:^(NSData *data, NSError *error) {
        [self endRefresh];
        
        if (data!=nil&&!error) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            if ([obj valueForKey: @"promptMessage"]) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"relogin" object:@"relogin"];
                
            }
            
            // NSArray *arr = [obj valueForKey:@"noticeMsg"];
            NSArray *leftArr = [obj valueForKey:@"notMsgList"];
            NSArray *rightArr = [obj valueForKey:@"readMsgList"];
            //msgList
            //notMsgList
            //这里添加功能判断
            NSString *NOMoreStr;
            NSString *NODataStr;
            if (getEnglishLanguage()) {
                
                    NOMoreStr = @"No more data";
                    NODataStr = @"No data";
                }else{
                    NOMoreStr = @"本页无更多数据";
                    NODataStr = @"本页无数据";
                }
            if (_openSwitch == 0) {//左侧未读消息
                NSString *count = [NSString stringWithFormat:@"%@",[obj objectForKey:@"notMsgCount"]];
                if ([count isEqualToString:@"0"]) {
                    
                    if (_isMore) {
                        [self showLabelWithText:NOMoreStr];
                        _isMore = NO;
                    }else{
                        [self showLabelWithText:NODataStr];
                    }
                    
                }
                if (_isRefresh == YES) {
                    _isRefresh = NO;
                    
                    [_leftArr removeAllObjects];
                }
                for (NSDictionary *dic in leftArr) {
                    MessageModel *mod = [[MessageModel alloc]init];
                    mod = [mod initWithDictionary:dic error:nil];
                    
                    if ([mod.if_seeCn isEqualToString:@"否"]) {
                        NSLog(@"+++++ 0.0 = =! 这里是未读的消息 != = 0.0 +++++");
                        [_leftArr addObject:mod];
                    }
                    
                    
                }
            }else{//右侧已读消息
                NSString *count = [NSString stringWithFormat:@"%@",[obj objectForKey:@"readMsgCount"]];
                if ([count isEqualToString:@"0"]) {
                    
                    if (_isMore) {
                        [self showLabelWithText:NOMoreStr];
                        _isMore = NO;
                    }else{
                        [self showLabelWithText:NODataStr];
                    }
                    
                }
                if (_isRefresh == YES) {
                    _isRefresh = NO;
                    
                    
                    [_rightArr removeAllObjects];
                }
                for (NSDictionary *dic in rightArr) {
                    MessageModel *mod = [[MessageModel alloc]init];
                    mod = [mod initWithDictionary:dic error:nil];
                    if ([mod.if_seeCn isEqualToString:@"是"]) {
                        NSLog(@"+++++ 0.0 = =! 这里是已读的消息 != = 0.0 +++++");
                        [_rightArr addObject:mod];
                    }
                }
            }
            
        }else{
            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:str];
        }
        
        [self.tbView reloadData];
        
    }];
}
#pragma mark - 删除请求
-(void)deleteRequest:(NSString *)deletID{
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:deletID forKeyedSubscript:@"delIds"];
    
    //    _start = _start + _limit;
    NSLog(@"%@",param);
    NSString *requestStr = [NSString stringWithFormat:@"%@%@", getBase(), deleteMessage_URL];
    [NetRequest requestUrl:requestStr andParamas:param andReturnBlock:^(NSData *data, NSError *error) {
        [self endRefresh];
        
        if (data!=nil&&!error) {
            // id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            if (_openSwitch == 0) {
                [_leftArr removeAllObjects];
                _leftStart = 0;
                
                NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
                NSString *badge = [ud objectForKey:@"badge"];
                NSInteger badgeIntValue = [badge integerValue];
                badgeIntValue -= [self.pickDeleteIndexArr count];
                badge = [NSString stringWithFormat:@"%zd",badgeIntValue];
                [ud setObject:badge forKey:@"badge"];
                
                [self dataRequest];
                
                
                
                [self.pickDeleteIndexArr removeAllObjects];
            }else{
                [_rightArr removeAllObjects];
                _rightStart = 0;
                [self dataRequest];
                [self.pickDeleteIndexArr removeAllObjects];
            }
            
            
        }else{
            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:str];
            [self.pickDeleteIndexArr removeAllObjects];
        }
        
        [self.tbView reloadData];
        
    }];
    
    
    
}
#pragma mark ---- 开关点击事件
- (void)leftBtnClick:(UIButton *)sender{
    if (_openSwitch == 0) {
        NSLog(@"点过了，已经在未读列表");
        return;
    }
    
    
    CGRect frame = _lineView.frame;
    frame.origin.x -= KWIDTH/2;
    [UIView animateWithDuration:0.5 animations:^{
        _lineView.frame = frame;
    }];
    [_rightBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
    [_leftBtn setTitleColor:[UIColor colorWithHex:0x5da6ff] forState:UIControlStateNormal];
    _openSwitch = 0;
    if (_ifNeedRefresh == YES) {
        _ifNeedRefresh = NO;
        [self dataRequest];
    }else{
        [self.tbView reloadData];
    }
    
}
- (void)rightBtnClick:(UIButton *)sender{
    
    if (_openSwitch == 1) {
        NSLog(@"点过了，已经在已读列表");
        return;
    }
    [_leftBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
    [_rightBtn setTitleColor:[UIColor colorWithHex:0x5da6ff] forState:UIControlStateNormal];
    
    CGRect frame = _lineView.frame;
    frame.origin.x += KWIDTH/2;
    [UIView animateWithDuration:0.5 animations:^{
        _lineView.frame = frame;
    }];
    
    
    _openSwitch = 1;
    if(_isFirstSelectRightBtn){
        _isFirstSelectRightBtn = NO;
        [self dataRequest];
    }else{
        
        [self.tbView reloadData];
    }
    
}
#pragma mark ---- 删除按钮点击事件
- (void)rightClick:(UIButton *)sender{
    if (_openSwitch == 0) {//左边
        if (_leftArr.count == 0) {
            return;
        }
    }else{
        if (_rightArr.count == 0) {
            return;
        }
    }
    _rightBtn.userInteractionEnabled = !_rightBtn.userInteractionEnabled;
    _leftBtn.userInteractionEnabled = !_leftBtn.userInteractionEnabled;
    CGFloat frameForY = self.selectbgView.frame.origin.y;
    CGFloat frameForHeight = KHEIGHT-self.tbView.frame.origin.y;
    NSLog(@"%f%f",frameForHeight,frameForY);
    if ((frameForHeight - frameForY)>40) {
        _editStage = YES;
    }else{
        _editStage = NO;
    }
    
    if (_editStage == NO) {//进入编辑界面
        [self.tbView setEditing:YES animated:YES];
        _editStage = YES;
        CGRect frame = self.tbView.frame;
        frame.size.height -= 40;
        CGRect bgFrame = self.selectbgView.frame;
        bgFrame.origin.y -=40;
        
        
        [UIView animateWithDuration:0.5 animations:^{
            self.tbView.frame = frame;
            self.selectbgView.frame = bgFrame;
        }];
    }else{//取消编辑界面
        [self.pickDeleteIndexArr removeAllObjects];
        [self.tbView setEditing:NO animated:YES];
        _editStage = NO;
        CGRect frame = self.tbView.frame;
        CGRect bgFrame = self.selectbgView.frame;
        bgFrame.origin.y +=40;
        frame.size.height += 40;
        [UIView animateWithDuration:0.5 animations:^{
            self.tbView.frame = frame;
            //            _doneBtn.frame = doneFrame;
            //            _cancelBtn.frame = cancelFrame;
            self.selectbgView.frame = bgFrame;
        }];
    }
}

- (void)cancelBtnClick:(UIButton *)sender{
    NSLog(@"取消了");
    [self.pickDeleteIndexArr removeAllObjects];
    if (_leftBtn.userInteractionEnabled == NO) {
        _leftBtn.userInteractionEnabled = YES;
    }
    if (_rightBtn.userInteractionEnabled == NO) {
        _rightBtn.userInteractionEnabled = YES;
    }
    [self.tbView setEditing:NO animated:YES];
    _editStage = NO;
    
    CGRect frame = self.tbView.frame;
    CGRect bgFrame = self.selectbgView.frame;
    bgFrame.origin.y +=40;
    frame.size.height += 40;
    [UIView animateWithDuration:1 animations:^{
        self.selectbgView.frame = bgFrame;
        self.tbView.frame = frame;
    }];
    
}

- (void)doneBtnClick:(UIButton *)sender{
    NSLog(@"确定后也取消了");
    //    [self.tbView setEditing:NO animated:YES];
    //    _editStage = NO;
    if (self.pickDeleteIndexArr.count == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"删除消息不能为空，请选择要删除的消息！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {//取消删除功能，可以重新选择删除项
            NSLog(@"qu取消了");
            
            
        }];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
        if (_leftBtn.userInteractionEnabled == NO) {
            _leftBtn.userInteractionEnabled = YES;
        }
        if (_rightBtn.userInteractionEnabled == NO) {
            _rightBtn.userInteractionEnabled = YES;
        }
        [self.tbView setEditing:NO animated:YES];
        _editStage = NO;
        
        CGRect frame = self.tbView.frame;
        CGRect bgFrame = self.selectbgView.frame;
        bgFrame.origin.y +=40;
        frame.size.height += 40;
        [UIView animateWithDuration:1 animations:^{
            self.selectbgView.frame = bgFrame;
            self.tbView.frame = frame;
        }];
        
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认要删除吗？" preferredStyle:UIAlertControllerStyleAlert];
        
        //    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {//取消删除功能，可以重新选择删除项
            NSLog(@"qu取消了");
            
            
        }];
        UIAlertAction *cancelAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {//确定删除并调用接口。
            NSLog(@"delete");
            NSLog(@"%@",_pickDeleteIndexArr);
            NSMutableArray *mainIdArr = [[NSMutableArray alloc] init];
            for (NSIndexPath *index in self.pickDeleteIndexArr) {
                MessageModel *model;
                if (_openSwitch == 0) {//左侧未读列表
                    if (_leftArr.count > index.row) {
                        model = [_leftArr objectAtIndex:index.row];
                    }else{
                        NSLog(@"什么鬼❓👻出错了！！！！");
                    }
                    
                    NSString *str = [NSString stringWithFormat:@",%@",model.mainId];
                    [mainIdArr addObject:str];
                }else{
                    if (_rightArr.count > index.row) {
                        model = [_rightArr objectAtIndex:index.row];
                    }else{
                        NSLog(@"什么鬼❓👻出错了！！！！");
                    }
                    NSString *str = [NSString stringWithFormat:@",%@",model.mainId];
                    [mainIdArr addObject:str];
                }
            }
            
            NSLog(@"%@",mainIdArr);
            NSMutableString *delIds = [[NSMutableString alloc] init];
            for (NSString *str in mainIdArr) {
                [delIds appendString:str];
            }
            [delIds deleteCharactersInRange:NSMakeRange(0, 1)];
            NSLog(@"%@",delIds);
            
            [self deleteRequest:delIds];
            
            
            
            if (_leftBtn.userInteractionEnabled == NO) {
                _leftBtn.userInteractionEnabled = YES;
            }
            if (_rightBtn.userInteractionEnabled == NO) {
                _rightBtn.userInteractionEnabled = YES;
            }
            
            //        btn.enabled = YES;
            CGRect frame = self.tbView.frame;
            CGRect bgFrame = self.selectbgView.frame;
            bgFrame.origin.y +=40;
            frame.size.height += 40;
            [UIView animateWithDuration:1 animations:^{
                self.selectbgView.frame = bgFrame;
                self.tbView.frame = frame;
            }];
            _editStage = NO;
            [self.tbView setEditing:NO animated:YES];
            
            
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:cancelAction1];
        
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


-(UITableViewCellEditingStyle )tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}

- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [[UIButton alloc] init];
        [self.selectbgView addSubview:_cancelBtn];
        [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_selectbgView.mas_left);
            make.right.equalTo(self.doneBtn.mas_left);
            make.width.equalTo(self.doneBtn.mas_width);
            make.top.equalTo(_selectbgView.mas_top);
            make.height.equalTo(@(40));
        }];
        [_cancelBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:32/2];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        //
    }
    return _cancelBtn;
}

- (UIButton *)doneBtn{
    if (!_doneBtn) {
        _doneBtn = [[UIButton alloc] init];
        
        [self.selectbgView addSubview:_doneBtn];
        
        [_doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_selectbgView.mas_right);
            make.top.equalTo(self.cancelBtn.mas_top);
            make.height.equalTo(@(40));
        }];
        [_doneBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
        _doneBtn.titleLabel.font = [UIFont systemFontOfSize:32/2];
        [_doneBtn setTitle:@"确定" forState:UIControlStateNormal];
    }
    return _doneBtn;
}


#pragma mark - 创建UI
-(void)createUI{
    self.tbView = [[UITableView alloc]init];
    
    [self.view addSubview:self.tbView];
    self.tbView.delegate = self;
    self.tbView.dataSource = self;
    
    self.tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tbView.backgroundColor = [UIColor clearColor];
    
    UIView *switchView = [[UIView alloc] init];
    switchView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:switchView];
    [switchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.height.equalTo(@(40));
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
    }];
    
    
    UIView *vline = [[UIView alloc] init];
    [self.view addSubview:vline];
    vline.backgroundColor = [UIColor colorWithHex:0x858585];
    [vline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.leftBtn.mas_right).offset(-0.5);
        make.width.equalTo(@(1));
        make.height.equalTo(@(20));
        make.centerY.equalTo(self.leftBtn.mas_centerY);
    }];
    
    [self.leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    
    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(43);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    self.tbView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //        self. = 0;
        _limit = 20;
        _start = 0;
        [_pickDeleteIndexArr removeAllObjects];
        if (_openSwitch == 0) {
            _leftStart = 0;
        }else{
            _rightStart = 0;
        }
        _isRefresh = YES;
        [self dataRequest];
    }];
    
    self.tbView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        //        [_sourceArr removeAllObjects];
        if (_openSwitch == 0) {
            _leftStart += _limit;
        }else{
            _rightStart += _limit;
        }
        //        _start = _start + _limit;
        //        _limit = _limit;
        _isMore = YES;
        [self dataRequest];
    }];
    self.lineView.backgroundColor = [UIColor colorWithHex:0x5da6ff];
    
    
    
    
    [self.cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.doneBtn addTarget:self action:@selector(doneBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.tabbarView.hidden = YES;
}

- (void) updateView//更新视图
{
    [self.tbView reloadData];
}

-(void)endRefresh{//停止刷新
    [self.tbView.header endRefreshing];
    [self.tbView.footer endRefreshing];
}
#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_openSwitch == 0) {
        return _leftArr.count;
    }else if(_openSwitch == 1){
        return _rightArr.count;
    }
    return _sourceArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ID = @"id";
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[MessageTableViewCell alloc]initWithReuseIdentifier:ID];
    }
    
    NSLog(@"%zd",indexPath.row);
    MessageModel *model;
    if (_openSwitch == 0) {
        model = _leftArr[indexPath.row];
    }else if (_openSwitch == 1){
        model = _rightArr[indexPath.row];
    }else{
        model = _sourceArr[indexPath.row];
    }
    
    
    cell.model = model;
    if ([cell.model.if_see isEqualToString:@"1"]) {
        cell.badgeMessage.text = @"已读";
        cell.badgeMessage.backgroundColor = [UIColor colorWithHex:0xa9a9a9];
        cell.badgeMessage.hidden = NO;
        cell.labelMessageState.text = @"是";
    }else{
        cell.badgeMessage.text = @"未读";
        cell.badgeMessage.backgroundColor = [UIColor redColor];
        cell.badgeMessage.hidden = NO;
        cell.labelMessageState.text = @"否";
    }
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 386/2;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (_editStage == YES) {
        
        [self.pickDeleteIndexArr addObject:indexPath];
        NSLog(@"%@",_pickDeleteIndexArr);
        
    }else{
        
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        DetailViewController *dvc = [[DetailViewController alloc] init];
        if(_openSwitch == 1)
        {
            dvc.read = @"read";
        }
        MessageModel *model;
        if (_openSwitch == 0) {
            model = _leftArr[indexPath.row];
        }else if (_openSwitch == 1){
            model = _rightArr[indexPath.row];
        }else{
            model = _sourceArr[indexPath.row];
        }
        
        model.if_see = @"1";
        
        
        dvc.model = model;
        if ([dvc.model.if_seeCn isEqualToString:@"否"]) {
            NSUserDefaults *ud1 = [NSUserDefaults standardUserDefaults];
            NSInteger badge = [[ud1 objectForKey:@"badge"] integerValue];
            if (badge) {
                [UIApplication sharedApplication].applicationIconBadgeNumber = badge-1;
                [ud1 setObject:[NSString stringWithFormat:@"%zd",badge-1] forKey:@"badge"];
                [ud1 synchronize];
            }
            
            //        _indexPath = indexPath;
            
            
            
        }
        //    dvc.model.if_seeCn = @"是";
        //    dvc.model.if_see = @"1";
        //    dvc.model.if_seeCn = @"是";
        //    [_sourceArr replaceObjectAtIndex:indexPath.row withObject:dvc.model];
        
        MessageTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.badgeMessage.text = @"已读";
        cell.labelMessageState.text = @"是";
        cell.badgeMessage.backgroundColor = [UIColor whiteColor];
        //    cell.badgeMessage.hidden = YES;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        
        [self.tbView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        dvc.delegate = self;
        
        [self.navigationController pushViewController:dvc animated:YES];
        
    }
    
    
    
    
    
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.pickDeleteIndexArr removeObject:indexPath];
    NSLog(@"%@",_pickDeleteIndexArr);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 重写showLabel方法
-(void)showLabelWithText:(NSString *)text{
    if(self.requeatResultLabel!=nil)return;
    self.requeatResultLabel = [[UILabel alloc]init];
    self.requeatResultLabel.backgroundColor = [UIColor colorWithRed:30/255.0 green:25/255.0 blue:77/255.0 alpha:0.4];
    self.requeatResultLabel.textColor = [UIColor whiteColor];
    self.requeatResultLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.requeatResultLabel];
    if(CURRENTVERSION<9.0){
        self.requeatResultLabel.frame = CGRectMake(0, -25, self.view.bounds.size.width, 25);
        CGRect frame = self.requeatResultLabel.frame;
        self.requeatResultLabel.text = [NSString stringWithFormat:@"%@", text];
        self.requeatResultLabel.font = [UIFont systemFontOfSize:14];
        [self.view bringSubviewToFront:self.requeatResultLabel];
        [UIView animateWithDuration:1 animations:^{
            self.requeatResultLabel.frame = CGRectMake(0, 45, self.view.bounds.size.width, 25);
            
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:1 animations:^{
                self.requeatResultLabel.frame = frame;
            } completion:^(BOOL finished) {
                [self.requeatResultLabel removeFromSuperview];
                self.requeatResultLabel = nil;
            }];
        }];
    }else{
        self.requeatResultLabel.frame = CGRectMake(0, 43, self.view.bounds.size.width, 0);
        CGRect frame = self.requeatResultLabel.frame;
        self.requeatResultLabel.text = [NSString stringWithFormat:@"%@", text];
        self.requeatResultLabel.font = [UIFont systemFontOfSize:14];
        [self.view bringSubviewToFront:self.requeatResultLabel];
        [UIView animateWithDuration:1 animations:^{
            self.requeatResultLabel.frame = CGRectMake(0, 43, self.view.bounds.size.width, 25);
            
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:1 animations:^{
                self.requeatResultLabel.frame = frame;
            } completion:^(BOOL finished) {
                [self.requeatResultLabel removeFromSuperview];
                self.requeatResultLabel = nil;
            }];
        }];
        
    }
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
